"""artile文章视图"""
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

def to_article_list(request):
    """文章列表"""
    #模文章列表数据，采用key:vlue表示，字段属性：title,author,price,content,pub_date,status
    articles = [
        {'title':'Python','author':'张三','price':100,'content':'Python是一种高级编程语言','pub_date':'2023-05-01','status':0},
        {'title':'Java','author':'李四','price':200,'content':'Java是一种面向对象的编程语言','pub_date':'2023-05-02','status':1},
        {'title':'C++','author':'王五','price':300,'content':'C++是一种通用的编程语言','pub_date':'2023-05-03','status':0},
        {'title':'PHP','author':'赵六','price':400,'content':'PHP是一种服务器端脚本语言','pub_date':'2023-05-04','status':1},
        {'title':'JavaScript','author':'钱七','price':500,'content':'JavaScript是一种客户端脚本语言','pub_date':'2023-05-05','status':0},
        {'title':'Ruby','author':'孙八','price':600,'content':'Ruby是一种动态脚本语言','pub_date':'2023-05-06','status':1}

    ]
    return render(request, 'article/article.html',{'articles':articles})


class ArticleListView2(APIView):
    def get(self, request):
        print("========== 收到GET请求 ==========")
        # 模文章列表数据，采用key:vlue表示，字段属性：id,title,author,price,content,pub_date,status
        articles = [
            {'id':1,'title':'Python','author':'张三','price':100,'content':'Python是一种高级编程语言','pub_date':'2023-05-01','status':0},
            {'id':2,'title':'Java','author':'李四','price':200,'content':'Java是一种面向对象的编程语言','pub_date':'2023-05-02','status':1},
            {'id':3,'title':'C++','author':'王五','price':300,'content':'C++是一种通用的编程语言','pub_date':'2023-05-03','status':0},
            {'id':4,'title':'PHP','author':'赵六','price':400,'content':'PHP是一种服务器端脚本语言','pub_date':'2023-05-04','status':1},
            {'id':5,'title':'JavaScript','author':'钱七','price':500,'content':'JavaScript是一种客户端脚本语言','pub_date':'2023-05-05','status':0},
            {'id':6,'title':'Ruby','author':'孙八','price':600,'content':'Ruby是一种动态脚本语言','pub_date':'2023-05-06','status':1}
        ]
        return Response({'articles':articles},200)

from blog.mydb_util import MySqlSession,Article
class ArticleListView(APIView):
    def get(self, request):
        print("========== 收到GET请求 ==========")
        session = MySqlSession().get_session()
        list=session.query(Article).all()
        #list转换成json数组，使用json对象的dumps方法
        temp_list=[]
        for article in list:
            #转换成json对象
            temp_list.append({'id':article.id,'title':article.title,'author':article.author,'price':article.price,'content':article.content,'pub_date':article.pub_date,'status':article.status})
        session.close()
        # 模文章列表数据，采用key:vlue表示，字段属性：id,title,author,price,content,pub_date,status
        return Response({'articles':temp_list},200)



""" 8.6 演示异步请求数据"""
def to_article_list2(request):
    """文章列表"""
    return render(request, 'article/chapter8_6-article.html')
